//
//  HMProductDetailViewController.m
//  HMMarket
//
//  Created by maimaigo3 on 2017/5/17.
//  Copyright © 2017年 homai. All rights reserved.
//

#import "HMProductDetailViewController.h"
#import "HMAddCartView.h"
#import "HMProDetailImageTableViewCell.h"
#import "HMProductSizeTableViewCell.h"
#import "HMCartController.h"
#import "SearchModel.h"
#import "HMItemDescTableViewCell.h"
#import "HMLoginController.h"
#import "HMHtmlTableViewCell.h"
@interface HMProductDetailViewController ()<UITableViewDelegate, UITableViewDataSource, HMAddCartViewDelegate, HMProductSizeTableViewCellDelegate, UIWebViewDelegate>
NS_STRONG UITableView *myTableView;
NS_STRONG HMAddCartView *addCartView;
NS_STRONG SearchModel *searchModel;
NS_STRONG NSMutableDictionary *keepSizeDict;
NS_STRONG UIImageView *imageVI;
NS_STRONG UIWebView *baseWebView;
@end

@implementation HMProductDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpSubView];
}

- (void)setUpSubView {
    _myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, -20, KWidthSCREEN, KHeightSCREEN) style:UITableViewStyleGrouped];
    _myTableView.delegate = self;
    _myTableView.dataSource = self;
    [self.view addSubview:_myTableView];
    
    _addCartView = [[HMAddCartView alloc] initWithFrame:CGRectMake(0, KHeightSCREEN - 49, KWidthSCREEN, 49)];
    _addCartView.delegate = self;
    _addCartView.numberOfCart = _cartNumber;
    [self.view addSubview:_addCartView];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setImage:[UIImage imageNamed:@"Cart_back"] forState:UIControlStateNormal];
    backBtn.frame = CGRectMake(20, 30, 40, 40);
    [backBtn addTarget:self action:@selector(gonBack) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backBtn];
    
    [self getData];
    DefaultWeakSelf;
    [DataSingleton sharedPerson].refreshCartNum = ^{
        weakSelf.addCartView.numberOfCart = [[DataSingleton sharedPerson].cartNum integerValue];
        //        weakSelf.addCartView.numberOfCart = [[DataSingleton sharedPerson].cartNum integerValue];
    };
}

- (void)getData {
    [HttpBaseTool get:kGoodsDes params:@{@"item_id":_pro_id} success:^(id responseObj) {
        _searchModel = [SearchModel mj_objectWithKeyValues:responseObj[@"data"]];
        
         [self.imageVI sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",kImageUrl,_searchModel.logo]]];
        [_myTableView reloadData];
        [self keepBaseSizeArray];
        [self setFootView];
    } failure:^(NSError *error) {
        
    }];
}

- (void)setFootView {
    _baseWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, KWidthSCREEN, 0.1)];
    self.baseWebView.delegate = self;

    [self.baseWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://sale.hmwuliu.com/particulars.html?item_id=%@", _searchModel.id]]]];
    [self.baseWebView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
    
    self.myTableView.tableFooterView = _baseWebView;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"contentSize"]) {
        CGRect rect =  self.baseWebView.frame;
        CGSize size = [self.baseWebView sizeThatFits:CGSizeZero];
        _baseWebView.frame = CGRectMake(rect.origin.x, rect.origin.y, KWidthSCREEN, size.height);
        self.myTableView.contentSize = CGSizeMake(KWidthSCREEN, rect.origin.y + size.height);
    }
}

#pragma mark - UIWebViewDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    CGFloat height = 0.0;

//    NSInteger height = [[webView stringByEvaluatingJavaScriptFromString: @"document.body.scrollHeight"] floatValue];
//    CGFloat height = [[self.baseWebView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] floatValue];
//    CGRect rect =  webView.frame;
    MyLog(@"height  === %lf", height);
    MyLog(@"sizeThatFits  === %lf", [self.baseWebView sizeThatFits:CGSizeZero].height);
    MyLog(@"stringByEvaluatingJavaScriptFromString  === %lf", [[webView stringByEvaluatingJavaScriptFromString: @"document.body.scrollHeight"] floatValue]);
    
    CGFloat documentWidth = [[webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('content').offsetWidth"] floatValue];
    CGFloat documentHeight = [[webView stringByEvaluatingJavaScriptFromString:@"document.getElementById(\"content\").offsetHeight;"] floatValue];
    NSLog(@"documentSize = {%f, %f}", documentWidth, documentHeight);
    
    
    
//    _baseWebView.frame = CGRectMake(rect.origin.x, rect.origin.y, KWidthSCREEN, height);
    MyLog(@"_baseWebView == %@", _baseWebView);
}

- (void)keepBaseSizeArray {
    _keepSizeDict = [NSMutableDictionary dictionary];
    for (int i = 0; i < _searchModel.attr.count; i++) {
        NSDictionary *stringDict = _searchModel.attr[i];
        NSArray *dataArr = [stringDict[@"attr_value"] componentsSeparatedByString:@","];
        [self.keepSizeDict setObject:[dataArr firstObject] forKey:stringDict[@"attr_name"]];
    }
}

- (void)gonBack {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - HMAddCartViewDelegate
- (void)addCart {
    [self completeSelect];
}

- (void)completeSelect {
    [self.view endEditing:YES];
    NSArray *keyArray = [self.keepSizeDict allKeys];
    NSString *item_attr = @"";
    for (int i = 0; i < keyArray.count; i++) {
        if (i == 0) {
            item_attr = [NSString stringWithFormat:@"%@:%@", keyArray[i], self.keepSizeDict[keyArray[i]]];
        } else {
            NSString *attr = [NSString stringWithFormat:@"%@:%@", keyArray[i], self.keepSizeDict[keyArray[i]]];
            item_attr = [NSString stringWithFormat:@"%@,%@", item_attr, attr];
        }
    }
    NSDictionary *parm = @{@"user_tel":[MGAccountTool getTel], @"item_id":_searchModel.id, @"item_number":self.addCartView.numberTextField.text, @"item_price":_searchModel.item_price, @"item_attr":item_attr};
    DefaultWeakSelf;
    [HttpBaseTool post:kAddCart params:parm success:^(id responseObj) {
        if ([responseObj[@"code"] integerValue] == 200) {
            LoginSuccess;
//            NSInteger number = _addCartView.numberOfCart + 1;
//            number ++;
//            MyLog(@"%ld", number);
//            _addCartView.numberOfCart = number;
            [HMHUDManager showHUDWithText:@"添加成功"];
//            self.addCartView.numberOfCart = [[DataSingleton sharedPerson].cartNum integerValue];
            [DataSingleton sharedPerson].refreshCartNum = ^{
                weakSelf.addCartView.numberOfCart = [[DataSingleton sharedPerson].cartNum integerValue];
//                if ([_delegate respondsToSelector:@selector(refreshCartNumer)]) {
//                    [_delegate refreshCartNumer];
//                }
            };
            [self.myTableView reloadData];
            
            
            
            [self.view addSubview:self.imageVI];
            [UIView animateWithDuration:1.0 animations:^{
                _imageVI.frame = CGRectMake(40, KHeightSCREEN - 49, 20, 20);
                _imageVI.alpha = 0.5;
            }];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [_imageVI removeFromSuperview];
            });
            
        } else {
            [HMHUDManager showHUDWithText:responseObj[@"msg"]];
        }
    } failure:^(NSError *error) {
        
    }];
}

- (void)noLogin {
    HMLoginController *vc = [[HMLoginController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - HMProductSizeTableViewCellDelegate
- (void)clickSize:(NSString *)sender {
    MyLog(@"%@", sender);
}

- (void)pushToCartVC {
    if ([MGAccountTool getUsername] == nil) { // 之前没有登录成功
        HMLoginController * login = [[HMLoginController alloc] init];
        UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:login];
        [self.navigationController presentViewController:nav animated:YES completion:nil];
    } else {
        HMCartController *vc = [[HMCartController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }

}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 3;
    } else if (section == 1) {
        return _searchModel.attr.count;
    } else {
        return 1;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if ([HMReductionData replaceNullValue:_searchModel.item_desc].length == 0) {
        return 2;
    } else {
        return 3;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            HMProDetailImageTableViewCell *cell = [[[NSBundle mainBundle] loadNibNamed:@"HMProDetailImageTableViewCell" owner:self options:nil] firstObject];
            [cell.proImageVI sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",kImageUrl,_searchModel.logo]]];
            return cell;
        } else {
            static NSString *identi = @"cell";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identi];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identi];
            }
            if (indexPath.row == 1) {
                cell.textLabel.text = _searchModel.item_name;
            } else {
                cell.textLabel.text = [NSString stringWithFormat:@"¥%@/%@", _searchModel.item_price, _searchModel.weight];
                cell.textLabel.textColor = [UIColor redColor];
                int shulaing = arc4random_uniform(2000);
                cell.detailTextLabel.text = [NSString stringWithFormat:@"月销量%d笔",shulaing];
            }
            return cell;
        }
    } else if (indexPath.section == 1) {
        static NSString *identi = @"HMProductSizeTableViewCell";
        HMProductSizeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identi];
        if (cell == nil) {
            cell = [[HMProductSizeTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identi];
            cell.dataDict = _searchModel.attr[indexPath.row];
        }
        cell.delegate = self;
        return cell;
    } else {
        HMItemDescTableViewCell *cell = [[[NSBundle mainBundle] loadNibNamed:@"HMItemDescTableViewCell" owner:self options:nil] firstObject];
        cell.descLabel.text = _searchModel.item_desc;
        return cell;
    }
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0 && indexPath.section == 0) {
        return 325;
    } else {
        return 44;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 2) {
        return 10;
    }
    return 0.001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.001;
}

#pragma mark - HMProductSizeTableViewCellDelegate
- (void)clickSize:(NSString *)selectString attr_id:(NSString *)attr_id {
    [self.keepSizeDict setObject:selectString forKey:attr_id];
}

//cell 分割线 两端封头 实现这个两个方法 1
-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    if ([_myTableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [_myTableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([_myTableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [_myTableView setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    _baseWebView.delegate = nil;
}

- (UIImageView *)imageVI {
    if (_imageVI == nil) {
        _imageVI = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, KWidthSCREEN, 325)];

    } else {
        _imageVI.frame = CGRectMake(0, 0, KWidthSCREEN, 325);
    }
    return _imageVI;
}

@end
